const fs = require('fs').promises;
const WebSocket = require('ws');
const config = require('../config/config');
const { sanitizeMessage } = require('../utils/helpers');

class MessageService {
  constructor(chatService) {
    this.chatService = chatService;
    this.messageHistory = [];
  }

  async loadHistory() {
    try {
      const data = await fs.readFile(config.LOG_FILE, 'utf8');
      const lines = data.split('\n').filter(line => line.trim());
      this.messageHistory = lines.map(line => JSON.parse(line)).slice(-config.MAX_HISTORY);
    } catch (error) {
      if (error.code !== 'ENOENT') {
        console.error('加载历史消息失败:', error);
      }
    }
  }

  async saveMessage(message) {
    try {
      const logEntry = JSON.stringify(message) + '\n';
      await fs.appendFile(config.LOG_FILE, logEntry, 'utf8');
      this.messageHistory.push(message);
      if (this.messageHistory.length > config.MAX_HISTORY) {
        this.messageHistory.shift();
      }
    } catch (error) {
      console.error('保存消息失败:', error);
    }
  }

  sendHistory(ws) {
    if (ws.readyState === WebSocket.OPEN) {
      this.messageHistory.forEach(msg => {
        ws.send(JSON.stringify(msg));
      });
    }
  }

  sendWelcomeMessages(ws, clientId) {
    this.chatService.sendSystemMessage(ws, '欢迎来到聊天室！请设置你的昵称。');
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({
        type: 'setClientId',
        clientId: clientId
      }));
    }
  }

  async handleChatMessage(clientId, message) {
    const client = this.chatService.clientService.getClient(clientId);
    if (!client?.nickname) return;

    const msg = {
      type: 'message',
      clientId: clientId,
      nickname: client.nickname,
      message: sanitizeMessage(message),
      timestamp: Date.now()
    };

    await this.saveMessage(msg);
    this.chatService.broadcast(msg);
  }
}

module.exports = MessageService; 